package com.hliushi.oauth2.controller;

import com.hliushi.oauth2.pojo.User;
import com.hliushi.oauth2.service.UserService;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author llhuang10
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 获取当前用户
     *
     * @param authentication
     * @return
     */
    @GetMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication, HttpServletRequest request) {
        User user = new User("hliushi", "123456",
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));

        UserDetails userDetails = userService.loadUserByUsername("");

        // return new JsonResult<>(user);


        /**
         * bug点, 将request头信息需要加这个字段Authorization [授权]
         * 而不是 Authentication[认证], 之前在postman中header设置为Authentication
         * 导致出现了"error_description": "Full authentication is required to access this resource"
         */
        String head = request.getHeader("Authorization");
        String token = head.substring(head.indexOf("bearer") + 7);

        return Jwts.parser()
                .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }
}
